package com.shenfc.fxzj.action.admin;


import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.shenfc.fxzj.domain.Blog;
import com.shenfc.fxzj.domain.BlogType;
import com.shenfc.fxzj.domain.DataGridJson;
import com.shenfc.fxzj.domain.PageBean;
import com.shenfc.fxzj.service.BlogService;
import com.shenfc.fxzj.service.BlogTypeService;
import com.shenfc.fxzj.solr.BlogSolrIndex;
import com.shenfc.fxzj.util.HtmlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 管理员博客Controller层
 *
 * @author Administrator
 */
@Controller
@RequestMapping("/admin/blog")
public class BlogAdminAction extends BaseAction {

    @Autowired
    private BlogService blogService;
    @Autowired
    private BlogTypeService blogTypeService;

    // 博客索引
    private BlogSolrIndex blogIndex = new BlogSolrIndex();

    private static String content;

    private final static Logger log = LoggerFactory.getLogger(BlogAdminAction.class);

    @RequestMapping("/index")
    public ModelAndView index() throws Exception {
        return new ModelAndView("admin/blog/blogList");
    }

    @RequestMapping("/add")
    public ModelAndView add(Blog blog, String page, String type) throws Exception {
        ModelAndView mav = new ModelAndView();
        mav.addObject("type", type);
        List<BlogType> blogTypes = blogTypeService.queryBlogTypeList();
        mav.addObject("blogTypes", blogTypes);
        if (blog.getId() == null) {

        } else {
            Blog data = blogService.getBlogById(blog.getId());
            content = data.getContent();
            mav.addObject("data", data);
        }
        mav.setViewName("/admin/blog/blogAdd");
        return mav;
    }

    @RequestMapping("/getContent")
    @ResponseBody
    public JSONObject getContent(HttpServletResponse response) throws Exception {
        JSONObject result = new JSONObject();
        result.put("content", content);
        content = "";
        return result;
    }


    /**
     * 添加或者修改博客信息
     */
    @RequestMapping("/save")
    @ResponseBody
    public JSONObject save(Blog blog, HttpServletResponse response) throws Exception {
        JSONObject result = new JSONObject();
        try {
            if (blog.getId() == null) {
                blog.setUuid(UUID.randomUUID().toString());
                blog.setCreateTime(new Date());
                blog.setCreateUserId(1L);
                blogService.addBlog(blog);
                blogIndex.addIndex(blog); // 添加博客索引
            } else {
                blog.setUpdateTime(new Date());
                blog.setUpdateUserId(1L);
                blogService.update(blog);
                blogIndex.updateIndex(blog); // 更新博客索引
            }
            result.put("success", true);
            result.put("msg", "保存成功");
        } catch (Exception e) {
            log.error("博客保存失败", e);
            result.put("success", false);
            result.put("msg", "保存失败");
        }
        return result;
    }

    /**
     * 分页查询博客信息
     */
    @RequestMapping("/list")
    public void list(PageBean pageBean, Blog blog, HttpServletResponse response) {
        DataGridJson<Blog> dataGridJson = new DataGridJson<Blog>();
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("title", blog.getTitle());
            PageInfo<Blog> pageInfo = blogService.queryBlogPage(map, pageBean);
            List<Blog> blogList = pageInfo.getList();
            dataGridJson.setData(blogList);
            dataGridJson.setCount(pageBean.getRecTotal());
            HtmlUtil.writerJson(response, dataGridJson);
        } catch (Exception e) {
            dataGridJson.setCode(1);
            dataGridJson.setMsg("请求出现异常，请联系管理员！");
            HtmlUtil.writerJson(response, dataGridJson);
        }
    }

    @RequestMapping("/navs")
    public void navs(PageBean pageBean, Blog blog, HttpServletResponse response) {
        System.out.println(111);
            HtmlUtil.writerJson(response, "{\n" +
                    "\t\"contentManagement\": [\n" +
                    "\t\t{\n" +
                    "\t\t\t\"title\": \"文章列表1111\",\n" +
                    "\t\t\t\"icon\": \"icon-text\",\n" +
                    "\t\t\t\"href\": \"/admin/blog/index\",\n" +
                    "\t\t\t\"spread\": false\n" +
                    "\t\t},\n" +
                    "\t\t{\n" +
                    "\t\t\t\"title\": \"图片管理\",\n" +
                    "\t\t\t\"icon\": \"&#xe634;\",\n" +
                    "\t\t\t\"href\": \"page/img/images.html\",\n" +
                    "\t\t\t\"spread\": false\n" +
                    "\t\t},\n" +
                    "\t\t{\n" +
                    "\t\t\t\"title\": \"其他页面\",\n" +
                    "\t\t\t\"icon\": \"&#xe630;\",\n" +
                    "\t\t\t\"href\": \"\",\n" +
                    "\t\t\t\"spread\": false,\n" +
                    "\t\t\t\"children\": [\n" +
                    "\t\t\t\t{\n" +
                    "\t\t\t\t\t\"title\": \"404页面\",\n" +
                    "\t\t\t\t\t\"icon\": \"&#xe61c;\",\n" +
                    "\t\t\t\t\t\"href\": \"page/404.html\",\n" +
                    "\t\t\t\t\t\"spread\": false\n" +
                    "\t\t\t\t},\n" +
                    "\t\t\t\t{\n" +
                    "\t\t\t\t\t\"title\": \"登录\",\n" +
                    "\t\t\t\t\t\"icon\": \"&#xe609;\",\n" +
                    "\t\t\t\t\t\"href\": \"page/login/login.html\",\n" +
                    "\t\t\t\t\t\"spread\": false,\n" +
                    "\t\t\t\t\t\"target\": \"_blank\"\n" +
                    "\t\t\t\t}\n" +
                    "\t\t\t]\n" +
                    "\t\t}\n" +
                    "\t],\n" +
                    "\t\"memberCenter\": [\n" +
                    "\t\t{\n" +
                    "\t\t\t\"title\": \"用户中心\",\n" +
                    "\t\t\t\"icon\": \"&#xe612;\",\n" +
                    "\t\t\t\"href\": \"page/user/userList.html\",\n" +
                    "\t\t\t\"spread\": false\n" +
                    "\t\t},\n" +
                    "\t\t{\n" +
                    "\t\t\t\"title\": \"会员等级\",\n" +
                    "\t\t\t\"icon\": \"icon-vip\",\n" +
                    "\t\t\t\"href\": \"page/user/userGrade.html\",\n" +
                    "\t\t\t\"spread\": false\n" +
                    "\t\t}\n" +
                    "\t],\n" +
                    "\t\"systemeSttings\": [\n" +
                    "\t\t{\n" +
                    "\t\t\t\"title\": \"系统基本参数\",\n" +
                    "\t\t\t\"icon\": \"&#xe631;\",\n" +
                    "\t\t\t\"href\": \"page/systemSetting/basicParameter.html\",\n" +
                    "\t\t\t\"spread\": false\n" +
                    "\t\t},{\n" +
                    "\t\t\t\"title\": \"系统日志\",\n" +
                    "\t\t\t\"icon\": \"icon-log\",\n" +
                    "\t\t\t\"href\": \"page/systemSetting/logs.html\",\n" +
                    "\t\t\t\"spread\": false\n" +
                    "\t\t},{\n" +
                    "\t\t\t\"title\": \"友情链接\",\n" +
                    "\t\t\t\"icon\": \"&#xe64c;\",\n" +
                    "\t\t\t\"href\": \"page/systemSetting/linkList.html\",\n" +
                    "\t\t\t\"spread\": false\n" +
                    "\t\t},{\n" +
                    "\t\t\t\"title\": \"图标管理\",\n" +
                    "\t\t\t\"icon\": \"&#xe857;\",\n" +
                    "\t\t\t\"href\": \"page/systemSetting/icons.html\",\n" +
                    "\t\t\t\"spread\": false\n" +
                    "\t\t}\n" +
                    "\t],\n" +
                    "\t\"seraphApi\": [\n" +
                    "\t\t{\n" +
                    "\t\t\t\"title\": \"三级联动模块\",\n" +
                    "\t\t\t\"icon\": \"icon-mokuai\",\n" +
                    "\t\t\t\"href\": \"page/doc/addressDoc.html\",\n" +
                    "\t\t\t\"spread\": false\n" +
                    "\t\t},{\n" +
                    "\t\t\t\"title\": \"bodyTab模块\",\n" +
                    "\t\t\t\"icon\": \"icon-mokuai\",\n" +
                    "\t\t\t\"href\": \"page/doc/bodyTabDoc.html\",\n" +
                    "\t\t\t\"spread\": false\n" +
                    "\t\t},{\n" +
                    "\t\t\t\"title\": \"三级菜单\",\n" +
                    "\t\t\t\"icon\": \"icon-mokuai\",\n" +
                    "\t\t\t\"href\": \"page/doc/navDoc.html\",\n" +
                    "\t\t\t\"spread\": false\n" +
                    "\t\t}\n" +
                    "\t]\n" +
                    "}\n" +
                    "\n" +
                    "\n");
    }
    /**
     * 删除博客信息
     */
    @RequestMapping("/delete")
    @ResponseBody
    public JSONObject delete(@RequestParam(value = "ids[]", required = false) Long[] ids, String page, HttpServletResponse response) throws Exception {
        JSONObject result = new JSONObject();
        try {
            if (ids != null && ids.length > 0) {
                for (Long i : ids) {
                    Blog blog = blogService.getBlogById(i);
                    blogIndex.deleteIndex(blog.getUuid()); // 添加博客索引
                }
                blogService.deleteBlogBatch(ids);
            }
            result.put("success", true);
            result.put("msg", "删除成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("msg", "删除失败");
        }
        return result;
    }

    @RequestMapping("/uploadImg")
    public String uploadImg(HttpServletResponse response, HttpServletRequest request) {
        response.setContentType("text/html; charset=UTF-8");
        // 文件保存目录路径
        String savePath = request.getSession().getServletContext().getRealPath("/upload/");
        // 文件保存目录URL
        String saveUrl = request.getContextPath() + "/upload/";
        // 定义允许上传的文件扩展名
        String[] fileTypes = new String[]{"gif", "jpg", "jpeg", "png", "bmp"};
        // 最大文件大小
        long maxSize = 5242880L;
        PrintWriter out = null;
        try {
            out = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //创建一个通用的多部分解析器
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        //判断 request 是否有文件上传,即多部分请求
        if (multipartResolver.isMultipart(request)) {
            //转换成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            //取得request中的所有文件名
            Iterator<String> iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                //取得上传文件
                MultipartFile imgFile = multiRequest.getFile(iter.next());
                if (imgFile == null) {
                    System.out.println("请选择文件。");
                    return null;
                }
                //取得当前上传文件的文件名称
                String myFileName = imgFile.getOriginalFilename();
                if (imgFile.getSize() > maxSize) {
                    System.out.println("[ " + myFileName + " ]超过单个文件大小限制，文件大小[ " + imgFile.getSize() + " ]，限制为[ " + maxSize + " ] ");
                    return null;
                }
                // 创建文件夹
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                String ymd = sdf.format(new Date());
                savePath += "/" + ymd;
                saveUrl += ymd + "/";
                File dirFile = new File(savePath);
                if (!dirFile.exists()) {
                    dirFile.mkdirs();
                }
                // 检查目录写权限
//                if (!dirFile.canWrite()) {
//                    out.println(getError("上传目录没有写权限。"));
//                    return null;
//                }
                String suffix = myFileName.substring(myFileName.lastIndexOf(".") + 1).toLowerCase();
                if (!Arrays.<String>asList(fileTypes).contains(suffix)) {
                    System.out.println("上传文件扩展名[" + suffix + "]是不允许的扩展名。");
                    return null;
                }
                String newFileName = UUID.randomUUID().toString() + "." + suffix;
//                SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
//                String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
                try {
                    File localFile = new File(savePath, newFileName);
                    imgFile.transferTo(localFile);
                    JSONObject obj = new JSONObject();
                    obj.put("state", "SUCCESS");
                    obj.put("title", newFileName);
                    obj.put("original", myFileName);
                    obj.put("type", suffix);
                    obj.put("url", saveUrl + newFileName);
                    obj.put("size", imgFile.getSize() + "");
                    System.out.println(obj.toString());
                    out.println(obj.toString());
                    System.out.println("上传图片:[" + myFileName + "]" + ">>>[" + newFileName + "]成功");
                } catch (IOException e) {
                    System.out.println("图片上传失败:" + e.getMessage());
                }
                return null;
            }
        }
        return null;
    }
}
